import {
  changeContainerStatusReq,
  deleteContainer,
  inspectContainerReq,
  listContainerReq,
  viewDockerReq,
} from '@/api/docker'
import { $toast } from '@/hooks/customToast'
import { ListContainersParamsFilterTy } from '@/types/docker.type'
import { defineStore } from 'pinia'
import {
  exhaustMap,
  forkJoin,
  from,
  interval,
  mergeMap,
  takeWhile,
  tap,
} from 'rxjs'

export const useContainersStore = defineStore('container', {
  state: (): { containers: any[]; currentUser: string | undefined } => ({
    containers: [],
    currentUser: '',
  }),
  getters: {
    G_containers: (state) => state.containers,
  },
  actions: {
    M_handleError(error: any) {
      $toast.error(error, { position: 'top' })
    },
    M_setContainers(containers: any) {
      this.$patch({
        containers,
      })
    },
    M_setCurrentUser(username: string | undefined) {
      this.$patch({
        currentUser: username,
      })
    },

    /** docker 的一些操作  */

    M_showDocker() {
      return viewDockerReq()
    },
    //列出容器
    async M_listContainers(filters: ListContainersParamsFilterTy) {
      try {
        const containers = await listContainerReq(filters)
        this.M_setContainers(containers)
        console.log("列出容器",containers);
        
        return containers
      } catch (error: any) {
        this.M_handleError(error)
      }
    },
    //删除容器
    M_deleteContainers(containerIds?: string[]) {
      const ids = !containerIds
        ? this.containers.map((c) => c.Id)
        : containerIds
      if (ids) {
        const stream$ = forkJoin(ids!.map((i) => from(deleteContainer(i))))
        return stream$
      }
    },
    //改变容器状态
    M_changeContainerStatus(
      containerIds: string[],
      sign: 'start' | 'stop' | 'kill' | 'restart',
      state: 'running' | 'exited'
    ) {
      if (containerIds.length > 0) {
        const source$ = from(
          changeContainerStatusReq({
            id: containerIds[0],
            sign,
          })
        )
        source$.pipe(
          mergeMap((a) =>
            interval(1000).pipe(
              exhaustMap((v) => from(inspectContainerReq(containerIds[0]))),
              tap((q) => {
                console.log(q)
              }),
              takeWhile((b: any) => b.State.Status !== state)
            )
          )
        )

        return source$
      }
    },
  },
})
